package com.qh.resourcehub.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.error.OAuth2AuthenticationEntryPoint;

import javax.servlet.http.HttpServletResponse;

@Configuration
@Order(3)
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS).permitAll();

        http
                .authorizeRequests()
                .antMatchers(HttpMethod.POST,"/login","/logout","/**").permitAll();

        http
                .authorizeRequests()
                .antMatchers(HttpMethod.DELETE,"/logout").permitAll();

        http
                .csrf().disable()
                .exceptionHandling()
                .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
                .and()
                .authorizeRequests()
                .antMatchers(
                        "/oauth/token"
                        , "/sample/receiveOrder", "/websocket/**", "/js/**"
                        , "/api/file/download/**", "/api/file/downloads/**", "/api/file/showImage/**", "/api/file/showFile/**"
                        ,"/validateImg.jpg","/**"
                ).permitAll()
                .anyRequest().authenticated()
                .and()
                .httpBasic();

        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).sessionFixation().none();
    }


    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        OAuth2AuthenticationEntryPoint auth2AuthenticationEntryPoint = new OAuth2AuthenticationEntryPoint();
        resources.authenticationEntryPoint(auth2AuthenticationEntryPoint);
    }
}
